<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>成远生产管控平台 - 矿车载量信息查询</title>
    <style>
        :root {
            --primary-color: #009688;
            --secondary-color: #2F4056;
            --accent-color: #1E9FFF;
            --light-gray: #f5f7fa;
            --dark-gray: #393D49;
            --border-radius: 8px;
            --box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
        }

        body {
            margin: 0;
            padding: 0;
            min-height: 100vh;
            font-family: "Helvetica Neue", Helvetica, "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", Arial, sans-serif;
            font-size: 14px;
            color: #333;
            background-color: #f0f2f5;
            background-image: url('images/background.jpeg');
            background-size: cover;
            background-position: center;
            background-repeat: no-repeat;
        }

        /* 全局组件样式 */
        .layui-table th,
        .layui-form-label,
        .layui-btn {
            font-weight: 500;
        }

        .layui-table td {
            font-size: 13px;
        }

        .layui-btn {
            border-radius: var(--border-radius);
            transition: all 0.3s ease;
        }

        .layui-btn-primary:hover {
            border-color: var(--primary-color);
            color: var(--primary-color);
        }

        .layui-form-select dl dd.layui-this {
            background-color: var(--primary-color);
        }

        .layui-form-checked[lay-skin="primary"] i {
            border-color: var(--primary-color);
            background-color: var(--primary-color);
        }

        .layui-tab-title li {
            font-weight: 500;
        }

        .layui-tab-title.layui-this {
            color: var(--primary-color);
        }

        .layui-tab-title.layui-this:after {
            border-bottom: 2px solid var(--primary-color);
        }

        /* 页面结构样式 */
        .header-container {
            background-color: #ffffff;
            padding: 15px 30px;
            box-shadow: var(--box-shadow);
            display: flex;
            justify-content: space-between;
            align-items: center;
            position: sticky;
            top: 0;
            z-index: 1000;
        }

        .header-left {
            display: flex;
            align-items: center;
        }

        .header-logo {
            display: flex;
            align-items: center;
            margin-right: 20px;
            padding-right: 20px;
            border-right: 1px solid #eee;
        }

        .header-logo i {
            font-size: 24px;
            color: var(--primary-color);
            margin-right: 10px;
        }

        .header-title {
            margin: 0;
            font-size: 18px;
            font-weight: 600;
        }

        .header-info {
            color: #666;
        }

        .header-right {
            display: flex;
            align-items: center;
        }

        .user-info {
            display: flex;
            align-items: center;
            margin-right: 20px;
        }

        .user-avatar {
            width: 32px;
            height: 32px;
            border-radius: 50%;
            background-color: var(--primary-color);
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-right: 10px;
        }

        .logout-btn {
            background-color: #ff5722;
            color: white;
        }

        .logout-btn:hover {
            background-color: #d84a1d;
        }

        .content-container {
            background-color: rgba(255, 255, 255, 0.95);
            border-radius: var(--border-radius);
            box-shadow: var(--box-shadow);
            padding: 20px;
            margin: 20px;
        }

        .section-title {
            font-size: 20px;
            font-weight: 600;
            margin-bottom: 20px;
            color: var(--secondary-color);
            display: flex;
            align-items: center;
        }

        .section-title i {
            margin-right: 10px;
            color: var(--primary-color);
        }

        /* 表格样式优化 */
        .layui-table {
            border-radius: var(--border-radius);
            overflow: hidden;
        }

        .layui-table thead tr {
            background-color: #f8f9fa;
        }

        .layui-table th {
            font-weight: 600;
            color: var(--secondary-color);
        }

        .layui-table tbody tr:hover {
            background-color: #f5f8ff;
        }

        /* 统计信息样式 */
        .statistics-container {
            padding: 15px 20px;
            background-color: #f0f2f5;
            border-radius: var(--border-radius);
            margin-top: 20px;
            font-weight: 500;
            color: var(--secondary-color);
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .statistics-item {
            display: flex;
            align-items: center;
        }

        .statistics-item i {
            margin-right: 8px;
            color: var(--primary-color);
        }

        .statistics-value {
            font-weight: 600;
            color: #ff5722;
            margin-left: 5px;
        }

        /* 响应式设计 */
        @media screen and (max-width: 1200px) {
            .header-container {
                flex-direction: column;
                padding: 15px;
            }

            .header-left,.header-right {
                width: 100%;
                justify-content: center;
            }

            .header-logo {
                border-right: none;
                margin-right: 0;
                padding-right: 0;
                margin-bottom: 10px;
            }

            .user-info {
                margin-right: 0;
                margin-bottom: 10px;
            }
        }

        @media screen and (max-width: 768px) {
            .content-container {
                margin: 10px;
                padding: 15px;
            }

            .section-title {
                font-size: 18px;
            }

            .statistics-container {
                flex-direction: column;
                align-items: flex-start;
            }

            .statistics-item {
                margin-bottom: 10px;
            }
        }
    </style>
</head>
<body>
<!-- 顶部导航栏 -->
<div class="header-container">
    <div class="header-left">
        <div class="header-logo">
            <i class="fa fa-cogs"></i>
            <h3 class="header-title">成远生产管控平台</h3>
        </div>
        <div class="header-info">
            <p style="margin: 0;">欢迎您，<span id="usernameDisplay"></span>！</p>
            <p style="margin: 0;">当前时间：<span id="currentTime"></span></p>
        </div>
    </div>
    <div class="header-right">
        <div class="user-info">
            <div class="user-avatar"><i class="fa fa-user"></i></div>
            <span id="usernameDisplayMobile"></span>
        </div>
        <button class="layui-btn logout-btn" id="logoutBtn">
            <i class="fa fa-sign-out"></i> 退出系统
        </button>
    </div>
</div>

<!-- 内容区域 -->
<div class="content-container">
    <div class="section-title">
        <i class="fa fa-search"></i>
        矿车载量信息查询
    </div>

    <div class="layui-form-item">
        <div class="layui-input-block" style="text-align: center;">
            <button class="layui-btn" id="exportBtn">
                <i class="fa fa-download"></i> 导出Excel
            </button>
        </div>
    </div>

    <table id="dataTable" class="layui-table" lay-filter="dataTable"></table>

    <div class="statistics-container">
        <div class="statistics-item">
            <i class="fa fa-balance-scale"></i>
            <span>总重量:</span>
            <span class="statistics-value" id="totalWeight">0.00</span>
            <span>吨</span>
        </div>
        <div class="statistics-item">
            <i class="fa fa-cubes"></i>
            <span>总体积:</span>
            <span class="statistics-value" id="totalVolume">0.00</span>
            <span>立方米</span>
        </div>
        <div class="statistics-item">
            <i class="fa fa-truckRecord"></i>
            <span>总记录:</span>
            <span class="statistics-value" id="totalCount">0</span>
            <span>条</span>
        </div>
    </div>
</div>
<!-- Font Awesome -->
<link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
<!-- Moment.js -->
<script src="https://cdn.jsdelivr.net/npm/moment@2.29.4/moment.min.js"></script>
<!-- jQuery -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<!-- Layui -->
<link rel="stylesheet" href="./layui/css/layui.css"/>
<script src="./layui/layui.js"></script>
<!-- SheetJS (XLSX) -->
<script src="https://cdn.jsdelivr.net/npm/xlsx@0.18.5/dist/xlsx.full.min.js"></script>
<!-- FileSaver.js -->
<script src="https://cdn.jsdelivr.net/npm/file-saver@2.0.5/dist/FileSaver.min.js"></script>
<script>
    layui.use(['form', 'jquery', 'table', 'layer'], function () {
        const $ = layui.$,
            form = layui.form,
            table = layui.table,
            layer = layui.layer;

        // 更新当前时间
        function updateCurrentTime() {
            const now = moment().format('YYYY年MM月DD日 HH:mm:ss');
            $('#currentTime').text(now);
            $('#currentTimeMobile').text(now);
        }

        setInterval(updateCurrentTime, 1000);
        updateCurrentTime(); // 初始化一次

        // 获取当前用户的用户名和所属单位ID
        const username = sessionStorage.getItem('username');
        const unitId = sessionStorage.getItem('unitId');

        // 检查 unitId 是否存在，如果不存在则跳转到登录页面
        if (!username ||!unitId) {
            layer.msg('请先登录系统', {icon: 2});
            setTimeout(() => {
                window.location.href = '/login.html';
            }, 1500);
            return;
        }

        // 显示欢迎信息
        function displayUsername(username) {
            $('#usernameDisplay').text(username);
            $('#usernameDisplayMobile').text(username);
        }
        displayUsername(username);

        // 初始化表格
        const dataTable = table.render({
            elem: '#dataTable',
            url: `http://localhost:8080/truckRecord/trucksByUnit/${unitId}`,
            cols: [[
                {field: 'id', title: '序号', width: 80},
                {field: 'uuid', title: '唯一标识符', minWidth: 120},
                {field: 'gate', title: '门岗', width: 100},
                {field: 'belonging', title: '施工单位', width: 120},
                {field: 'plate', title: '车牌号', width: 120},
                {field: 'time', title: '时间', width: 140},
                {field:'material', title: '材料', width: 100},
                {field: 'density', title: '密度', width: 100, templet: d => (d.density || 0).toFixed(2)},
                {field: 'volume', title: '体积(m³)', width: 100, templet: d => (d.volume || 0).toFixed(2)},
                {field: 'weight', title: '重量(吨)', width: 100, templet: d => (d.weight || 0).toFixed(2)},
                {field:'scan', title: '扫描状态', width: 100, templet: d => d.scan?
                        '<span class="layui-badge layui-bg-green">已扫描</span>' :
                        '<span class="layui-badge layui-bg-orange">未扫描</span>'
                },
                {field:'status', title: '同步状态', width: 100, templet: d => d.status?
                        '<span class="layui-badge layui-bg-green">已同步</span>' :
                        '<span class="layui-badge layui-bg-orange">未同步</span>'
                }
            ]],
            page: true,
            limit: '',
            limits: [10,20,50,100,500,1000],
            response: {
                statusCode: 0, // 成功状态码
                countName: 'count', // 数据总数的字段名
                dataName: 'data' // 数据列表的字段名

            },
            request: {
                pageName: 'page',   // 默认就是 page
                limitName: 'size'   // 关键！告诉 Layui 把 limit 转换为 size
            },
            done: function (res) {
                // 显示统计结果
                const totalWeight = res.totalWeight!== undefined? res.totalWeight : 0;
                const totalVolume = res.totalVolume!== undefined? res.totalVolume : 0;
                const totalCount = res.count!== undefined? res.count : 0;

                $('#totalWeight').text(totalWeight.toFixed(2));
                $('#totalVolume').text(totalVolume.toFixed(2));
                $('#totalCount').text(totalCount);
            },
            error: function (res) {
                console.error('查询失败，状态码：', res.status, '响应内容：', res.responseText);
                layer.msg('查询失败');
            }
        });

        // 将表格数据转换为适合导出的格式
        function transformTableData(data) {
            const columnMapping = {
                id: '序号',
                uuid: '唯一标识符',
                gate: '门岗',
                belonging: '施工单位',
                plate: '车牌号',
                time: '时间',
                material: '材料',
                density: '密度',
                volume: '体积',
                weight: '重量',
                scan: '扫描状态',
                status: '同步状态'
            };
            return data.map(item => {
                const transformedItem = {};
                for (const key in item) {
                    if (columnMapping[key] && key!== 'LAY_TABLE_INDEX' && key!== 'unitId') {
                        transformedItem[columnMapping[key]] = item[key];
                    }
                }
                transformedItem['扫描状态'] = item.scan === 1? '已扫描' : '未扫描';
                transformedItem['同步状态'] = item.status === 1? '已同步' : '未同步';
                return transformedItem;
            });
        }

        // 获取全部数据（考虑分页情况）
        async function getAllTableData(tableInstance) {
            const allData = [];
            const { limit, page } = tableInstance.config;
            const totalPages = Math.ceil(tableInstance.config.count / limit);
            const fetchPageData = async (pageNum) => {
                const res = await $.ajax({
                    url: tableInstance.config.url,
                    data: {
                        page: pageNum,
                        size: limit
                    }
                });
                allData.push(...res.data);
            };
            const fetchAllPages = async () => {
                for (let i = 1; i <= totalPages; i++) {
                    await fetchPageData(i);
                }
                return allData;
            };
            return fetchAllPages();
        }

        async function getAllTableDataRefresh(tableInstance) {
            const unitId = sessionStorage.getItem('unitId');
            if (!unitId) {
                layer.msg('单位ID无效', { icon: 2 });
                return [];
            }

            try {
                const res = await $.ajax({
                    url: 'http://localhost:8080/truckRecord/exportAllByUnit',
                    method: 'GET',
                    data: {
                        unitId: unitId
                    }
                });

                console.log('导出数据:', res.data);
                return res.data || [];

            } catch (error) {
                console.error('获取全部数据失败:', error);
                layer.msg('获取数据失败，请重试', { icon: 2 });
                return [];
            }
        }

        // 定义导出Excel的函数
        function exportToExcel(data, filename) {
            try {
                // 创建工作簿
                const workbook = XLSX.utils.book_new();
                // 将数据转换为工作表
                const worksheet = XLSX.utils.json_to_sheet(data);
                // 将工作表添加到工作簿
                XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1');
                // 生成Excel文件
                const excelBuffer = XLSX.write(workbook, {
                    bookType: 'xlsx',
                    type: 'array'
                });
                // 创建Blob对象
                const blob = new Blob([excelBuffer], { type: 'application/octet-stream' });
                // 保存文件
                saveAs(blob, filename + '.xlsx');
                layer.msg('导出成功');
            } catch (error) {
                if (error instanceof TypeError) {
                    layer.msg('导出失败: 数据格式错误，请检查表格数据');
                } else {
                    layer.msg('导出失败:'+ error.message);
                }
            }
        }

        // 验证文件名
        function validateFileName(filename) {
            const maxLength = 50; // 设置文件名最大长度
            if (filename.length > maxLength) {
                layer.msg('文件名过长，请缩短文件名');
                return false;
            }
            // 去除常见非法字符
            filename = filename.replace(/[\\/*?:"<>|]/g, '');
            // 进一步检查特殊字符等，可根据需要扩展
            return true;
        }

        // 绑定导出按钮的点击事件
        $('#exportBtn').on('click', async function () {
            const loadingIndex = layer.load(1); // 显示加载动画
            const data = await getAllTableDataRefresh(dataTable);
            layer.close(loadingIndex);
            if (!data || data.length === 0) {
                layer.msg('没有数据可导出');
                return;
            }

            let filename = prompt('请输入要保存的文件名（不包含扩展名）', '矿车载量信息');
            if (filename === null) {
                // 用户取消了输入
                return;
            }

            if (!validateFileName(filename)) {
                return;
            }

            const transformedData = transformTableData(data);

            // 调用导出函数
            exportToExcel(transformedData, filename);
        });

        // 绑定退出按钮的点击事件
        $('#logoutBtn').on('click', function () {
            layer.confirm('确定要退出系统吗？', {
                icon: 3,
                title: '确认退出'
            }, function (index) {
                // 清除 sessionStorage 中的用户信息
                sessionStorage.clear();
                // 跳转到登录页面
                window.location.href = '/login.html';
                layer.close(index);
            });
        });
    });
</script>
</body>
</html>